package com.csf.controller;

import com.csf.config.likeKeyConfig;
import com.csf.entity.*;
import com.csf.event.EventProducer;
import com.csf.service.CommentService;
import com.csf.service.DiscussPostService;
import com.csf.service.UserService;
import com.csf.service.likeService;
import com.csf.util.CommunityActivation;
import com.csf.util.communityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static com.csf.util.CommunityActivation.ENTITY_TYPE_COMMENT;
import static com.csf.util.CommunityActivation.ENTITY_TYPE_POST;

@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityActivation {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;
//session的替代
    @Autowired
    private SessionReplace sessionReplace;
//点赞
    @Autowired
    private likeService likeService;
//评论
    @Autowired
    private CommentService commentService;
//redis
    @Autowired
    private RedisTemplate redisTemplate;
//kafka
    @Autowired
    private EventProducer eventProducer;

    @RequestMapping(value = "/findDis")
    public String findDiscussPost(Model model, Page page,
//                                  处理最热和最新的列表显示/如果等于零则最新显示，如果等于1则是最热显示
                                  @RequestParam(name = "orderMode",defaultValue = "0") int orderMode){
//        获取总行数
        page.setRows(discussPostService.DiscussPostRows(0));
//        获取当前路径
        page.setPath("/discuss/findDis?orderMode="+orderMode);
        List<DiscussPost> discussPostList = discussPostService.findDiscussPost(0, page.getiniRows(), page.getLimit(),orderMode);
        List<Map<String,Object>> maplist = new ArrayList<>();
        if (discussPostList != null){
            for (DiscussPost disList:discussPostList) {
                User user = userService.findUserById(disList.getUserId());
                Map<String,Object> map = new HashMap<>();
                map.put("user",user);
                map.put("disList",disList);
//                判断点了多少个赞
                int likeCount = likeService.likeCount(ENTITY_TYPE_POST, disList.getId());
                map.put("likeDisCount",likeCount);

                maplist.add(map);
            }
        }
        model.addAttribute("maplist",maplist);
        model.addAttribute("orderMode",orderMode);
        return "index";
    }


    @RequestMapping(value = "/insertDis",method = RequestMethod.POST)
    @ResponseBody
    public String InsertDis(String title,String content){
        //当前必须有用户才能够写文章发布
        User user = sessionReplace.getUser();
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setTitle(title);
        discussPost.setContent(content);
        discussPost.setCreateTime(new Date());
//        存入用户
        discussPostService.insertDiscussPost(discussPost);

        Event event = new Event()
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(discussPost.getId())
                .setTopic(TOPIC_DISES);
        eventProducer.fireEvent(event);

//        记录发帖
        String postKey = likeKeyConfig.getPostKey();
        redisTemplate.opsForSet().add(postKey,discussPost.getId());

//        存入成功
        return communityUtils.getJsonString(0,"发布成功");
    }

    @RequestMapping(value = "/detail/{id}",method = RequestMethod.GET)
    public String detail(@PathVariable("id") int id,Model model,Page page){

        DiscussPost post = discussPostService.selectDisById(id);
        model.addAttribute("post",post);
        User user = userService.findUserById(post.getUserId());
        model.addAttribute("localuser",user);


//        查看当前帖子有多少个赞
        int countLike = likeService.likeCount(ENTITY_TYPE_POST, post.getId());
        model.addAttribute("countLike",countLike);
        //查看当前登录人员是否给当前帖子点赞
        int likeStatus = sessionReplace.getUser() == null? 0:likeService.likeStatus(sessionReplace.getUser().getId(),ENTITY_TYPE_POST, post.getId());
        model.addAttribute("likeStatus",likeStatus);


//        设置分页
        page.setLimit(5);
        page.setRows(post.getCommentCount());
        page.setPath("/discuss/detail/"+id);

//      查看评论消息
        List<Comment> comments = commentService.findCommentList(ENTITY_TYPE_POST, post.getId(), page.getiniRows(), page.getLimit());
        List<Map<String,Object>> mapList = new ArrayList<>();
        if (mapList != null){
        for (Comment comment : comments) {
            Map<String,Object> map = new HashMap<>();
                map.put("comment",comment);
//                评论的人是谁
                map.put("CommentUser",userService.findUserById(comment.getUserId()));

//          查看对本评论的赞
            int CommentCount = likeService.likeCount(ENTITY_TYPE_COMMENT, comment.getId());
            model.addAttribute("CommentLikeCount",CommentCount);
//            当前用户对本评论是否赞过
            int isAddLike = sessionReplace.getUser() == null ? 0:likeService.likeStatus(sessionReplace.getUser().getId(),ENTITY_TYPE_COMMENT, comment.getId());
            model.addAttribute("isAddlike",isAddLike);

//                从当前评论中获取可能回复评论的人的所有信息
            List<Comment> reCommentList = commentService.findCommentList(
                    ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
            List<Map<String,Object>> RemapList = new ArrayList<>();
//            获取回复人的所有信息
            if (reCommentList != null){
                for (Comment reComment : reCommentList) {
                    Map<String,Object> remap = new HashMap<>();
                    remap.put("reComment",reComment);
//                    回复评论的评论的人是谁
                    remap.put("reCommentUser",userService.findUserById(reComment.getUserId()));
//                    回复目标(当点击回复的时候，会产生target，如果是普通帖子回复，则为空，如果不是帖子回复而是评论回复，则会查找当前评论人辕信息)
                    User targetUser = reComment.getTargetId() == 0 ? null : userService.findUserById(reComment.getTargetId());
                    remap.put("targetUser",targetUser);

//          查看对本评论的赞
                    int reCommentCount = likeService.likeCount(ENTITY_TYPE_COMMENT, reComment.getId());
                    model.addAttribute("reCommentCount",reCommentCount);
//            当前用户对本评论是否赞过
                    int reisAddLike = sessionReplace.getUser() == null ? 0:likeService.likeStatus(sessionReplace.getUser().getId(),ENTITY_TYPE_COMMENT, reComment.getId());
                    model.addAttribute("reisAddlike",reisAddLike);

                    RemapList.add(remap);
                }
            }
             map.put("replaceMap",RemapList);
            //                   查看评论回复数量
            int Recount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
            map.put("reCount",Recount);

            mapList.add(map);
        }
        }
        model.addAttribute("mapListComment",mapList);
        return "site/discuss-detail";
    }

//    错误页面
    @RequestMapping(value = "/error",method = RequestMethod.GET)
    public String getErrorPage(){
        return "/error/505";
    }

    @RequestMapping(path = "/deny",method = RequestMethod.GET)
    public String getExcePage(){
        return "/error/404";
    }

//    对帖子进行置顶操作
    @RequestMapping(path = "/top",method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id){
        discussPostService.updateType(1,id);
//        置顶操作之后需要将改变后的数据存入es中
        Event event = new Event()
                .setUserId(sessionReplace.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id)
                .setTopic(TOPIC_DISES);
        eventProducer.fireEvent(event);

        return communityUtils.getJsonString(0);
    }

//   对帖子进行加精操作
    @RequestMapping(path = "/wonderful",method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id){
        discussPostService.updateStatus(1,id);
        //        置顶操作之后需要将改变后的数据存入es中
        Event event = new Event()
                .setUserId(sessionReplace.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id)
                .setTopic(TOPIC_DISES);
        eventProducer.fireEvent(event);
//加精操作会影响热度
        String postKey = likeKeyConfig.getPostKey();
        redisTemplate.opsForSet().add(postKey,id);

        return communityUtils.getJsonString(0);
    }

//    删除帖子
    @RequestMapping(path = "/deleteDis",method = RequestMethod.POST)
    @ResponseBody
    public String deleteDis(int id){
        discussPostService.updateStatus(2,id);
        //        置顶操作之后需要将改变后的数据存入es中
        Event event = new Event()
                .setUserId(sessionReplace.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id)
                .setTopic(TOPIC_DELETE);
        eventProducer.fireEvent(event);

        return communityUtils.getJsonString(0);
    }
}
